import { getAppInfo, getAppMeta, getAppParameters } from '@/api'
import type { IUserInputForm, IUserInputFormTypeEnums } from '@/types'
import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', {
  state: () => ({
    loaded: false,
    name: '',
    description: '',
    tags: [] as string[],
    openingStatement: '',
    userInputForm: undefined as IUserInputForm[] | undefined,
  }),
  getters: {
    needInputForm: (state) => {
      return !!state.userInputForm?.length
    },
    userInputFormItems: (state) => {
      return state.userInputForm?.map((item) => {
        const type = Object.keys(item)[0]
        const value = item[type as IUserInputFormTypeEnums]
        return {
          type,
          label: value.label,
          variable: value.variable,
          required: value.required,
          default: value.default,
          options: value.options,
        }
      })
    },
  },
  actions: {
    async loadApp() {
      await Promise.all([this.getAppInfo(), this.getAppParameters(), this.getAppMeta()])
      this.loaded = true
    },
    async getAppInfo() {
      try {
        const res = await getAppInfo()
        if (res) {
          this.name = res.name
          this.description = res.description
          this.tags = res.tags
        }
      } catch (error) {
        console.error('获取应用信息错误', error)
      }
    },
    async getAppParameters() {
      try {
        const res = await getAppParameters()
        if (res) {
          this.openingStatement = res.opening_statement
          this.userInputForm = res.user_input_form
          // this.name = res.name
          // this.description = res.description
          // this.tags = res.tags
        }
      } catch (error) {
        console.error('获取应用参数错误', error)
      }
    },
    async getAppMeta() {
      try {
        const res = await getAppMeta()
        if (res) {
        }
      } catch (error) {
        console.error('获取应用Meta错误', error)
      }
    },
  },
})
